<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>ajax-upload</title>
    <link href="https://cdn.bootcss.com/bootstrap/4.0.0/css/bootstrap.css" rel="stylesheet">
    <style>
        .progress-area {
            padding: 20px;
        }
    </style>
    <script src="js/jquery.min.js"></script>
</head>
<body>
<div class="">
    <p>文件上传</p>
    <div>
        <input type="file" name="file" id="crowd_file" />
        <div>
            <p>图片预览（如果上传文件时图片）</p>
            <div class="img-preview">
            </div>
        </div>
        <button id="upload">上传</button>
        <button id="btn">终止上传</button>
        <div class="progress-area">
            进度
            <div class="progress">
                <div class="progress-bar" id="progress" role="progressbar"  aria-valuenow="25" aria-valuemin="0" aria-valuemax="100">0%</div>
            </div>
            <div>
                <p id="time"></p>
            </div>
        </div>
    </div>
</div>
<script>
    $( "#crowd_file" ).change( function(){
        alert("开始");
        var crowd_file = $("#crowd_file")[0].files[0];

        var formData = new FormData();

        formData.append("file",$("#crowd_file")[0].files[0]);
        $.ajax({
            url:  '/ajax_upload',
            type:  'POST' ,
            Accept: 'text/html;charset=UTF-8' ,
            cache:  false ,
            contentType: "multipart/form-data" ,
            data:  formData,
            processData:  false ,
            contentType:  false ,
            xhr: function(){
                myXhr = $.ajaxSettings.xhr();
                if (myXhr.upload){  // check if upload property exists
                    myXhr.upload.addEventListener( 'progress' , function(e){
                        var  loaded = e.loaded; //已经上传大小情况
                        var  tot = e.total; //附件总大小
                        var  per =  Math .floor( 100 *loaded/tot);  //已经上传的百分比
                        $( "#progress" ).html( per + "%"  );
                        $( "#progress" ).css( "width"  , per + "%" );

                        console.log( '附件总大小 = '  + loaded);
                        console.log( '已经上传大小 = '  + tot);
                    },  false );  // for handling the progress of the upload
                }
                return  myXhr;
            },success:function(data){
                console.log(data);
                console.log("上传成功!!!!");
            },error:function(){
                console.log("上传失败！");
            }
        });
    });
</script>
</body>
</html>